import re
import os
import sys
from os import popen
from random import randint
import ml
import mysqldb as mysql
from ldaputils import *
import ldap.modlist

class projectsManager:
    def __init__(self, name, www, mysqldb, mysqlpass):
        self.name = name
        self.www = www
        self.mysqldb = mysqldb
        self.mysqlpass = mysqlpass
        self.genGid()
        print self.gid
        self.genUid()
        self.makeModList()
        ml.createMl(self.name, self.name)
        
    def genGid(self):
        while True:
            self.gid = randint(1001, 2000)
            out = popen("getent group | grep " +str(self.gid) + " | awk -F: '{print $3}'").read()
            if not out:
                break
    
    def genUid(self):
        self.uid = self.gid
        while True:
            out = popen("getent passwd | grep " +str(self.uid) + " | awk -F: '{print $3}'").read()
            if not out:
                break
            else:
                self.uid = randint(1001, 2000)

    def makeModList(self):
        self.pmlist = ldap.modlist.addModlist({
        "cn":str(self.name),
        "objectClass":["posixGroup", "apacheConfig"],
        "gidNumber":str(self.gid),
        "apacheServerName":str(self.www),
        "apacheDocumentRoot":str("/home/projects/%s"%self.name),
        "apacheSuexecUid":str(self.uid),
        "apacheSuexecGid":str(self.gid),
        "memberUid":"www-data"
        })
        
        self.umlist = ldap.modlist.addModlist({
        "uid":str(self.name),
        "cn":str("%s-user"%self.name),
        "objectClass":["account", "posixAccount", "shadowAccount"],
        "gidNumber":str(self.gid),
        "uidNumber":str(self.uid),
        "homeDirectory":str("/home/projects/%s"%self.name)
        })

    def save(self):
        l = ldapConnect()
        dn = "cn=%s,ou=projects,o="dbsolution sas",dc=localnet,dc=org"%self.name
        l.add_s(dn, self.pmlist)
        dn = "uid=%s,cn=%s,ou=projects,o="dbsolution sas",dc=localnet,dc=org"%(self.name, self.name)
        l.add_s(dn, self.umlist)
        self.createDirectory()
        if self.mysqldb:
            mysql.createDb(self.name, self.name, self.mysqlpass)

    def createDirectory(self):
        home = "/home/projects/%s" %self.name
        if not os.access(home, os.F_OK):
            popen("ldapmanager/apps/core/utility/projects home %s %s" %(self.name, self.gid)).read()
        #    os.mkdir(home)
        #    os.chown(home, -1, self.gid)

        svn = "/svnroot/%s" %self.name
        if not os.access(svn, os.F_OK):
            popen("ldapmanager/apps/core/utility/projects svn %s %s" %(self.name, self.gid)).read()
        #    popen("svnadmin create %s" %svn)
        #    popen("chown -R :%s %s" %(self.gid, svn))
        #    popen("chmod -R 770 %s" %svn)
